package com.ruoyi.user.cron;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.redis.RedisUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.date.DateUtil;
import com.ruoyi.common.utils.date.DateUtils;
import com.ruoyi.dynamic.mapper.UserDynamicMapper;
import com.ruoyi.system.domain.PriceSetting;
import com.ruoyi.system.mapper.PriceSettingMapper;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.domain.UserConversationRecord;
import com.ruoyi.user.mapper.UserConversationRecordMapper;
import com.ruoyi.user.mapper.UserMapper;
import com.ruoyi.user.service.IUserService;

import cn.hutool.core.collection.CollectionUtil;
/**
 * 	用户相关定时任务
 * @author DEREK
 *
 */
@Component
@EnableScheduling
@Async
public class UserTaskCron {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private UserDynamicMapper userDynamicMapper;
	@Autowired
	private PriceSettingMapper priceSettingMapper;

	@Autowired
	private UserConversationRecordMapper userConversationRecordMapper;
	@Autowired
	private IUserService userService;


	// 去重
	public Long retObjId(String qc1,String qc2) {
		Long objId = 0L;
		try {
			String qc3 = "";
			String[] arrqc1 = qc1.split(",");

			for(int i = 0;i <arrqc1.length;i++) {
				qc2.indexOf(arrqc1[i]);
				if (qc2.indexOf(arrqc1[i]) == -1) {
					qc3 +=  arrqc1[i] + ",";
				}
			}
			//去掉最后一个  ','
			qc3 = qc3.toString().substring(0,qc3.length()-1);
			System.out.println("qu3= "+qc3);
			if(StringUtils.isNotEmpty(qc3)) {
				objId = Long.valueOf(qc3.split(",")[0]);
			}

		} catch (Exception e) {
			e.printStackTrace();
			return objId;
		}
		return objId;
	}

	public static void main(String[] args) {
		String time = "2024-08-12 23:52:32";

		Date updTime = DateUtil.parse("yyyy-MM-dd HH:mm:ss", time);
		String format = DateUtil.format(updTime, "HH:mm:ss");
		String now = DateUtil.format(new Date(), "yyyy-MM-dd");

		Date parse = DateUtil.parse("yyyy-MM-dd HH:mm:ss", now+" "+format);

		long expireTime = DateUtils.getDaySecond(new Date(), parse);
		System.out.println(expireTime);
	}


	// 自动动态
	public void dynamicAuto() {
		// 动态
		String dynamicKeyAuto = "dynamic_auto0812";
		String dynamicIsOkAuto = "dynamic_ok_auto0812";
		Object obj = redisUtil.get(dynamicKeyAuto);
		if(null == obj) {
			return;
		}
		// 所有的动态ID 逗号区分
		String dynamicIds = obj.toString();
		// 要更新的动态ID
		Long dynamicId = 0L;
		Object object = redisUtil.get(dynamicIsOkAuto);
		if(null == object) {
			dynamicId = Long.valueOf(dynamicIds.split(",")[0]);
			redisUtil.set(dynamicIsOkAuto, dynamicIds.split(",")[0]);
		}else {
			Long retObjId = retObjId(dynamicIds, object.toString());
			if(retObjId == 0) {
				redisUtil.del(dynamicIsOkAuto);
				dynamicAuto();
				return;
			}
			dynamicId = retObjId;
			redisUtil.set(dynamicIsOkAuto, object.toString()+","+retObjId);
		}
		String expTimeKey = "dynamic-"+dynamicId+"-sweet";

		String time = "2024-08-12 18:52:32";
		Object object2 = redisUtil.get("dynamic_auto_time");
		if(null != object2) {
			time = object2.toString();
		}
		Date updTime = DateUtil.parse("yyyy-MM-dd HH:mm:ss", time);
		String format = DateUtil.format(updTime, "HH:mm:ss");
		String now = DateUtil.format(new Date(), "yyyy-MM-dd");

		Date parse = DateUtil.parse("yyyy-MM-dd HH:mm:ss", now+" "+format);

		long expireTime = DateUtils.getDaySecond(new Date(), parse);
		redisUtil.set(expTimeKey, dynamicId,expireTime);
	}

	// 自动派对
	public void partyAuto() {
		// 动态
		String partyKeyAuto = "party_auto0812";
		String partyIsOkAuto = "party_ok_auto0812";
		Object obj = redisUtil.get(partyKeyAuto);
		if(null == obj) {
			return;
		}
		// 所有的动态ID 逗号区分
		String dynamicIds = obj.toString();
		// 要更新的动态ID
		Long dynamicId = 0L;
		Object object = redisUtil.get(partyIsOkAuto);
		if(null == object) {
			dynamicId = Long.valueOf(dynamicIds.split(",")[0]);
			redisUtil.set(partyIsOkAuto, dynamicIds.split(",")[0]);
		}else {
			Long retObjId = retObjId(dynamicIds, object.toString());
			if(retObjId == 0) {
				redisUtil.del(partyIsOkAuto);
				partyAuto();
				return;
			}
			dynamicId = retObjId;
			redisUtil.set(partyIsOkAuto, object.toString()+","+retObjId);
		}
		String expTimeKey = "party-"+dynamicId+"-sweet";;

		String time = "2024-08-12 19:53:33";
		Object object2 = redisUtil.get("party_auto_time");
		if(null != object2) {
			time = object2.toString();
		}
		Date updTime = DateUtil.parse("yyyy-MM-dd HH:mm:ss", time);
		String format = DateUtil.format(updTime, "HH:mm:ss");
		String now = DateUtil.format(new Date(), "yyyy-MM-dd");

		Date parse = DateUtil.parse("yyyy-MM-dd HH:mm:ss", now+" "+format);

		long expireTime = DateUtils.getDaySecond(new Date(), parse);
		redisUtil.set(expTimeKey, dynamicId,expireTime);
	}


	@Scheduled(cron = "0 0 * * * ?")
	public void updUserVip() {
		UpdateWrapper<User> updateWrapper = Wrappers.update();
		updateWrapper.lt("vip_expire_time", new Date());
		User user = new User();
		user.setVip(0);
		userMapper.update(user, updateWrapper);
		
		//		PriceSetting set = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>()
		//				.eq(PriceSetting::getPriceType, "dynamic_time").select(PriceSetting::getId,PriceSetting::getParentName).last("limit 1"));
		//		if(null == set || StringUtils.isEmpty(set.getPriceName())) {
		//			return;
		//		}

		// 更新动态
		//		String dynamicUpdKey = "dynamic-";
		//		String dyKey = "dynamic-automatic";
		//		String dynamicId = "";
		//		Object obj = redisUtil.get(dyKey);
		//		if(null != obj) {
		//			dynamicId = obj.toString();
		//		}
		//		String now = DateUtil.format(new Date(), "yyyy-MM-dd");
		//		Date updTime = DateUtil.parse("yyyy-MM-dd HH:mm", set.getPriceName());
		//		String format = DateUtil.format(updTime, "HH:mm");
		//		Date parse = DateUtil.parse("yyyy-MM-dd HH:mm", now+" "+format);
		//		Date pastDateTime = DateUtils.getPastDateTime(1, parse, 2);
		//		long expireTime = DateUtils.getDaySecond(parse, pastDateTime);
		//
		//		Long automaticDynamic = userDynamicMapper.automaticDynamic(dynamicId);
		//		if(null == automaticDynamic) {
		//			Long automaticDynamic2 = userDynamicMapper.automaticDynamic("");
		//			if(null != automaticDynamic2) {
		//				redisUtil.set(dyKey, String.valueOf(automaticDynamic2));
		//				redisUtil.set(dynamicUpdKey+automaticDynamic2, automaticDynamic2, expireTime+5);
		//			}
		//		}else {
		//			String value = String.valueOf(automaticDynamic);
		//			if(StringUtils.isNotEmpty(dynamicId)) {
		//				value = dynamicId+","+automaticDynamic;
		//			}
		//			redisUtil.set(dyKey, value);
		//			redisUtil.set(dynamicUpdKey+automaticDynamic, automaticDynamic, expireTime+5);
		//		}
		//
		//		// 更新派对
		//		String partyUpdKey = "party-";
		//		String pyKey = "party-automatic";
		//		String partyId = "";
		//		Object objpy = redisUtil.get(pyKey);
		//		if(null != objpy) {
		//			partyId = objpy.toString();
		//		}
		//		
		//		Long automaticPartyId = userDynamicMapper.automaticParty(partyId);
		//		if(null == automaticPartyId) {
		//			Long automaticPartyId2 = userDynamicMapper.automaticParty("");
		//			if(null != automaticPartyId2) {
		//				redisUtil.set(pyKey, String.valueOf(automaticPartyId2));
		//				redisUtil.set(partyUpdKey+automaticPartyId2, automaticPartyId2, expireTime);
		//			}
		//		}else {
		//			String value = String.valueOf(automaticPartyId);
		//			if(StringUtils.isNotEmpty(partyId)) {
		//				value = partyId+","+automaticPartyId;
		//			}
		//			redisUtil.set(pyKey, value);
		//			redisUtil.set(partyUpdKey+automaticPartyId, automaticPartyId, expireTime);
		//		}
	}

	// 每天晚上1点执行 自动发布动态和约玩
	@Scheduled(cron = "0 0 1 * * ?")
	public void autoPubDynamicAndParty() {
		dynamicAuto();
		partyAuto();
	}
	
	
	/**
	 * 	每天零点更新VIP用户在线邀约、解锁微信、解锁聊天次数
	 */
	@Scheduled(cron = "0 0 0 * * ?")
	public void setUserOnlineDuration() {
		UpdateWrapper<User> updateWrapper = Wrappers.update();
		updateWrapper.eq("vip", 0);
		User user = new User();
		user.setUnlockWechat(0);
		user.setChatCount(0);
		user.setInviteCount(0);
		userMapper.update(user, updateWrapper);
		// 根据等级 更新VIP权益
		List<User> userList = userMapper.selectList(new LambdaQueryWrapper<User>()
				.eq(User::getVip, 1).select(User::getId,User::getVipLevel));
		if(CollectionUtil.isNotEmpty(userList)) {
			userList.stream().forEach(u ->{
				PriceSetting set = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>()
						.eq(PriceSetting::getAmountType, 1).eq(PriceSetting::getExtend4, u.getVipLevel()).last("limit 1"));
				if(set != null ) {
					u.setUnlockWechat(Integer.valueOf(set.getExtend2()));
					u.setChatCount(Integer.valueOf(set.getExtend3()));
					u.setMessageCount(Integer.valueOf(set.getExtend5()));
				}
			});
		}
		userService.updateBatchById(userList);
		//		UpdateWrapper<User> updateWrapper0 = Wrappers.update();
		//		updateWrapper0.eq("vip", 1);
		//		user = new User();
		//		user.setInviteCount(10);
		//		user.setUnlockWechat(10);
		//		user.setChatCount(10);



		//		Object object = redisUtil.get(ProjectConstant.platformConstant.UNLOCKWECHATCOUNT);
		//		if(null != object) {
		//			user.setUnlockWechat(Integer.valueOf(object.toString()));
		//		}
		//		Object object2 = redisUtil.get(ProjectConstant.platformConstant.UNLOCKCHATCOUNT);
		//		if(null != object2) {
		//			user.setChatCount(Integer.valueOf(object2.toString()));
		//		}
		//		userMapper.update(user, updateWrapper0);
		//		PriceSetting set = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "解锁微信次数")
		//				.select(PriceSetting::getId,PriceSetting::getPriceName));
		//		if(null != set && StringUtils.isNotEmpty(set.getPriceName()) && Integer.valueOf(set.getPriceName()) > 0) {
		//			user.setUnlockWechat(Integer.valueOf(set.getPriceName()));
		//		}
		//		set = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "解锁聊天次数")
		//				.select(PriceSetting::getId,PriceSetting::getPriceName));
		//		if(null != set && StringUtils.isNotEmpty(set.getPriceName()) && Integer.valueOf(set.getPriceName()) > 0) {
		//			user.setChatCount(Integer.valueOf(set.getPriceName()));
		//		}

		// 设置非会员男性用户赠送聊天次数
		//		UpdateWrapper<User> updateWrapper1 = Wrappers.update();
		//		updateWrapper1.eq("vip", 0);
		//		updateWrapper1.eq("sex", "M");
		//		user = new User();
		//		user.setChatCount(2);
		//		PriceSetting set = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "男性聊天次数")
		//				.select(PriceSetting::getId,PriceSetting::getPriceName));
		//		if(null != set && StringUtils.isNotEmpty(set.getPriceName()) && Integer.valueOf(set.getPriceName()) > 0) {
		//			user.setChatCount(Integer.valueOf(set.getPriceName()));
		//		}
		//		userMapper.update(user, updateWrapper1);

		// 晚上12点清除所有聊天权限 
		userConversationRecordMapper.delete(new LambdaQueryWrapper<UserConversationRecord>());
	}
}
